<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		if($this->session->userdata('logged_in') == TRUE AND strtolower($this->uri->segment(2)) !== 'logout')
		{
			redirect($this->session->userdata('userType'));
		}
		$this->layout_view = 'application_no_side_bar_no_header';
		$this->load->model('M_users');
		$this->load->library(array('form_validation','token'));
		$this->load->helper(array('url','form'));
		$this->token->set_token();
	}
	
	public function index()
	{
		redirect();
	}
	
	private function _captcha()
	{
		$this->load->helper('captcha');
		$system_counted_hash = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
		$vals = array(
			'word'	 => substr(md5(rand(1,100).$system_counted_hash),3,rand(2,5)),
			'img_path'	 => './captcha/',
			'img_url'	 => base_url().'auth/captcha',
			'font_path'	 => './assets/_fonts/4.ttf',
			'img_width'	 => '150',
			'img_height' => 35,
			'expiration' => 7200
			);
		
		$cap = create_captcha($vals);
		$image['word'] = $cap['word'];
		$image['image'] ='<image src="'.base_url().'captcha/'.$cap['time'].'.jpg"/>';
		$image['link'] = './captcha/'.$cap['time'].'.jpg';

		return (object)$image;
	}

	/*12-6-12 Login authentication for user*/
	function login($userType = FALSE)
	{
		$this->view_data['system_message']= $this->_msg();
		$userType = strtolower(trim(htmlspecialchars($userType)));
		$allowed_login_types = array('registrar','teacher','admin','evaluation','finance','president','cashier','hrd','librarian','custodian','guidance','vice-principal','encoder');
		
		$userdata = array(
			'userid' => '',
			'username' => '',
			'userType' => '',
			'e_f_name' => '',
			'e_l_name' => '',
			'e_m_name' => '',
			'logged_in' => FALSE
		);
		
		$this->session->set_userdata($userdata);

		if(in_array($userType,$allowed_login_types))
		{
			$this->load->helper('file');//load helper file
			delete_files('./captcha');// delete all images in captcha folder
			$captcha = $this->_captcha(); //generate captcha
			$this->session->set_flashdata('image_url',$captcha->link); // save path of generated captcha to session
			$this->view_data['form_token'] = $this->token->get_token();//generate form token
			$this->load->library('form_validation');
			$this->form_validation->set_rules('username', 'username', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('password', 'password', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('fit', ' ', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('captcha_text', 'captcha', 'required|trim|htmlspecialchars');
			
			$this->view_data['userType'] = strtolower($userType);
			$this->view_data['captcha_image'] = $captcha->image;
			
			if($this->input->post('backstage_login'))
			{
				
				$_SESSION['username'] = $username = $this->input->post('username');
				//get captcha link from session
				$captcha_image_link = $this->session->flashdata('image_url');
		
				// check if XSF or XXS filtering
				if($this->token->validate_token($this->input->post('fit',TRUE)))
				{
					//run form validation
					if($this->form_validation->run() !== FALSE)
					{
						//hash the word
						$captcha_word = md5(strtolower($this->session->userdata('word')));
						$sent_captcha_text = md5(strtolower($this->input->post('captcha_text')));
						

						if($captcha_word == $sent_captcha_text)
						{
							if($userType=='vice-principal'){
								$userType='vice_principal';
							}

							if($this->M_users->verify_user($this->input->post(),$userType))
							{
								
								$fname = $this->session->userdata('e_f_name');
								$lname = $this->session->userdata('e_l_name');
								$this->logger('login','User: {'.$username.','.$fname.','.$lname.'} successfully logged in.');
								
								$this->token->destroy_token();//destroy token
								$this->session->set_userdata('word',''); //destroy captcha from session
								
								unlink($captcha_image_link);//delete captcha image from file
								
								$this->_msg('s','Log-in successful. Welcome! ',$userType); // redirect success
							}else{
								$this->logger('login','User: {'.$username.'} failed login attempt.');
								$this->token->destroy_token();//destroy token
								$this->session->set_userdata('word','');//destroy captcha from session
								unlink($captcha_image_link);//delete captcha image from file
								$this->_msg('e','Invalid username/password combination.','auth/login/'.$userType);// redirect failed
							}
						}else{
							$this->token->destroy_token();
							$this->session->set_userdata('word','');
							unlink($captcha_image_link);
							$this->_msg('e','Wrong captcha code entered.','auth/login/'.$userType);
						}
					}
				}else{
					$this->token->destroy_token();
					$this->session->set_userdata('word','');
					unlink($captcha_image_link);
					$this->_msg('e','Invalid username/password combination.','auth/login/'.$userType);
				}
			}else{
				$this->session->set_userdata('word',$captcha->word);
			}
		}else{
			redirect();
		}
	}
	
    function logout()
    {
		$usertype = $this->session->userdata('userType');
		$message = $this->_msg();
		
		$userdata = array(
			'userid' => '',
			'username' => '',
			'userType' => '',
			'e_f_name' => '',
			'e_l_name' => '',
			'e_m_name' => '',
			'logged_in' => FALSE
		);
		
		$this->session->set_userdata($userdata);

		if($message)
		{
			$this->_msg('s',$message,'auth/login/'.$usertype);
		}else{
			$this->_msg('n','You are now logout.','auth/login/'.$usertype);
		}
    }
}